<template>
    <div class="app-container">
        <a-layout>
            <a-layout-content class="content">
                <div class="content-wrapper">
                    <div class="container my-4">
                        <a-typography-title :level="1" align="center">📸 媒体对比结果</a-typography-title>
                        <!-- 输入表单 -->
                        <a-card class="sticky-form-wrapper mb-4">
                            <a-form
                                ref="formRef"
                                layout="vertical"
                                :model="formState"
                                @submit="handleSubmit"
                            >
                                <a-row :gutter="[16, 16]" align="middle">
                                    <!-- 左边文件夹 -->
                                    <a-col :span="10">
                                        <a-form-item
                                            field="folder1"
                                            label="左边文件夹路径（原图）"
                                            :rules="[{ required: true, message: '请输入左边文件夹路径' }]"
                                        >
                                            <a-input
                                                v-model="formState.folder1"
                                                placeholder="/path/to/folder1"
                                            />
                                        </a-form-item>
                                    </a-col>
                                    <!-- 右边文件夹 -->
                                    <a-col :span="10">
                                        <a-form-item
                                            field="folder2"
                                            label="右边文件夹路径（新图）"
                                            :rules="[{ required: true, message: '请输入右边文件夹路径' }]"
                                        >
                                            <a-input
                                                v-model="formState.folder2"
                                                placeholder="/path/to/folder2"
                                            />
                                        </a-form-item>
                                    </a-col>
                                    <!-- 提交按钮 - 居中显示 -->
                                    <a-col :span="4" style="text-align: center;">
                                        <a-form-item style="margin-bottom: 0;">
                                            <a-button
                                                style="margin-top: 22px"
                                                type="primary"
                                                html-type="submit"
                                                :loading="loading"
                                            >
                                                🔍 开始对比
                                            </a-button>
                                        </a-form-item>
                                    </a-col>
                                </a-row>
                            </a-form>
                        </a-card>
                        <!-- 标签页导航 + 统一操作按钮 -->
                        <div class="d-flex justify-content-between align-items-center mb-3 mt-10 ">
                            <a-tabs
                                v-model:active-key="activeTab"
                                type="card-gutter"
                                @change="handleTabChange"
                                lazy-load
                            >
                                <a-tab-pane key="same">
                                    <template #title>
                                        <a-badge :max-count="9999" :count="counts.same">
                                            ✅ 相同
                                        </a-badge>
                                    </template>
                                    <!-- 相同标签页 -->
                                    <div class="tab-content">
                                        <a-spin :loading="loadingResults" tip="正在加载对比结果..." style="width: 100%">
                                            <div v-if="results.same_results.length === 0" style="width: 100%"
                                                 class="row">
                                                <div class="col-24">
                                                    <a-result status="warning" title="该类别下暂无文件.">
                                                    </a-result>
                                                </div>
                                            </div>

                                            <a-row v-else class="grid-demo" :gutter="[24,24]">
                                                <a-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" :xxl="6"
                                                       v-for="item in results.same_results"
                                                       :key="item.name">
                                                    <result-card
                                                        :item="item"
                                                        :folder1="results.folder1"
                                                        :folder2="results.folder2"
                                                        :status="item.status"
                                                        :selected-items="selectedItems"
                                                        @checkbox-change="handleCheckboxChange"
                                                        @open-compare="openCompareModal"
                                                    />
                                                </a-col>
                                            </a-row>
                                        </a-spin>
                                    </div>
                                </a-tab-pane>
                                <a-tab-pane key="different">
                                    <template #title>
                                        <a-badge :max-count="9999" :count="counts.different">
                                            ⚠️不同
                                        </a-badge>
                                    </template>
                                    <div class="tab-content">
                                        <a-spin :loading="loadingResults" tip="正在加载对比结果..." style="width: 100%">
                                            <div v-if="results.diff_results.length === 0" style="width: 100%"
                                                 class="row">
                                                <div class="col-24">
                                                    <a-result status="warning" title="该类别下暂无文件.">
                                                    </a-result>
                                                </div>
                                            </div>
                                            <div v-else class="row">
                                                <div
                                                    v-for="item in results.diff_results"
                                                    :key="item.name"
                                                    class="col-12 col-sm-6 col-md-6 col-lg-4 col-xl-3 mb-3"
                                                >
                                                    <result-card
                                                        :item="item"
                                                        :folder1="results.folder1"
                                                        :folder2="results.folder2"
                                                        :status="item.status"
                                                        :selected-items="selectedItems"
                                                        @checkbox-change="handleCheckboxChange"
                                                        @open-compare="openCompareModal"
                                                    />
                                                </div>
                                            </div>
                                        </a-spin>
                                    </div>
                                </a-tab-pane>
                                <a-tab-pane key="missing_in_2">
                                    <template #title>
                                        <a-badge :max-count="9999" :count="counts.missing_in_2">
                                            ➕ 右边缺少
                                        </a-badge>
                                    </template>
                                    <div class="tab-content">
                                        <a-spin :loading="loadingResults" tip="正在加载对比结果..." style="width: 100%">
                                            <div v-if="results.missing_in_2.length === 0" style="width: 100%"
                                                 class="row">
                                                <div class="col-24">
                                                    <a-result status="warning" title="该类别下暂无文件.">
                                                    </a-result>
                                                </div>
                                            </div>
                                            <a-row v-else class="grid-demo" :gutter="[24,24]">
                                                <a-col :xs="24" :sm="12" :md="6" :lg="6" :xl="4" :xxl="4"
                                                       v-for="item in results.missing_in_2"
                                                       :key="item.name">
                                                    <result-card
                                                        :item="item"
                                                        :folder1="results.folder1"
                                                        :folder2="results.folder2"
                                                        :status="item.status"
                                                        :selected-items="selectedItems"
                                                        @checkbox-change="handleCheckboxChange"
                                                        @open-compare="openCompareModal"
                                                    />
                                                </a-col>
                                            </a-row>
                                        </a-spin>
                                    </div>
                                </a-tab-pane>
                                <a-tab-pane key="missing_in_1">
                                    <template #title>

                                        <a-badge :max-count="9999" :count="counts.missing_in_1"> ➖ 左边缺少</a-badge>
                                    </template>
                                    <div class="tab-content">
                                        <a-spin :loading="loadingResults" tip="正在加载对比结果..." style="width: 100%">
                                            <div v-if="results.missing_in_1.length === 0" style="width: 100%"
                                                 class="row">
                                                <div class="col-24">
                                                    <a-result status="warning" title="该类别下暂无文件.">
                                                    </a-result>
                                                </div>
                                            </div>
                                            <a-row v-else class="grid-demo" :gutter="[24,24]">
                                                <a-col :xs="24" :sm="12" :md="6" :lg="6" :xl="4" :xxl="4"
                                                       v-for="item in results.missing_in_1"
                                                       :key="item.name">
                                                    <result-card
                                                        :item="item"
                                                        :folder1="results.folder1"
                                                        :folder2="results.folder2"
                                                        :status="item.status"
                                                        :selected-items="selectedItems"
                                                        @checkbox-change="handleCheckboxChange"
                                                        @open-compare="openCompareModal"
                                                    />
                                                </a-col>
                                            </a-row>
                                        </a-spin>
                                    </div>
                                </a-tab-pane>
                                <template #extra>
                                    <!-- 统一操作按钮组 -->
                                    <div class="btn-group">
                                        <!-- 删除按钮 -->
                                        <a-popconfirm content="确定删除所选文件吗？" ok-text="是" cancel-text="否"
                                                      @ok="batchAction('delete')">
                                            <a-button
                                                v-if="selectedCount > 0"
                                                type="primary" status="danger"
                                                style="margin-right: 8px;"
                                            >
                                                🗑️ 删除 ({{ selectedCount }})
                                            </a-button>
                                        </a-popconfirm>

                                        <!-- 移动按钮 -->
                                        <a-popconfirm content="确定将所选文件从左边移动到右边吗？" ok-text="是" cancel-text="否"
                                                      @ok="batchAction('move')">
                                            <a-button
                                                v-if="selectedLeftCount > 0"
                                                type="primary"
                                                style="margin-right: 8px;"
                                            >
                                                📁 移动 ({{ selectedCount }})
                                            </a-button>
                                        </a-popconfirm>

                                        <a-button @click="selectAll">全选</a-button>
                                        <a-button @click="unselectAll" style="margin-left: 8px;">取消</a-button>
                                        <a-button @click="selectSide('left')" style="margin-left: 8px;">勾选左</a-button>
                                        <a-button @click="selectSide('right')" style="margin-left: 8px;">勾选右</a-button>
                                    </div>
                                </template>
                            </a-tabs>
                        </div>

                        <!-- 进度条 -->
                        <a-modal
                            v-model:visible="progressVisible"
                            :footer="null"
                            :closable="false"
                            :mask-closable="false"
                            :width="600"
                        >
                            <template #title>
                                {{ progressAction === 'move' ? '正在移动文件...' : '正在删除文件...' }}
                            </template>
                            <a-progress
                                :percent="progressPercent"
                                :show-text="false"
                                status="active"
                            />
                            <p class="mt-2 text-center">
                                操作进行中... ({{ progressCompleted }}/{{ progressTotal }})
                            </p>
                        </a-modal>
                    </div>

                </div>
                <a-back-top target-container="#basic-demo" :style="{position:'absolute'}"/>

            </a-layout-content>

            <a-layout-footer class="footer">
                www.heanny.cn ©2025
            </a-layout-footer>
        </a-layout>

        <!-- 图片对比模态框 -->
        <a-modal
            v-model:visible="compareVisible"
            title="图片对比"
            :footer="null"
            :closable="true"
            :mask-closable="true"
            :width="1200"
        >
            <a-row :gutter="[24,24]">
                <a-col :md="12" class="text-center">
                    <h3>原图（左边）</h3>
                    <div class="img-show">
                        <img :src="compareLeftSrc" alt="Left Image" class="img-fluid rounded shadow"/>
                    </div>
                </a-col>
                <a-col :md="12" class="text-center">
                    <h3>新图（右边）</h3>
                    <div class="img-show">
                        <img :src="compareRightSrc" alt="Right Image" class="img-fluid rounded shadow"/>
                    </div>
                </a-col>
            </a-row>
        </a-modal>
    </div>
</template>

<script setup>
import {
    ref,
    reactive,
    computed,
    onMounted
} from 'vue';
import {
    Form,
    Card,
    Row,
    Col,
    Input,
    Button,
    Tabs,
    TabPane,
    Badge,
    Spin,
    Modal,
    Progress,
    Message
} from '@arco-design/web-vue';

import ResultCard from './components/ResultCard.vue';
import {getMediaSrc} from './utils/utils'

const formRef = ref();
const formState = reactive({
    folder1: 'E:/1/photo/Meizu',
    folder2: 'E:/1/test/2'
});

const loading = ref(false);
const loadingResults = ref(false);
// const results = ref(null);
let results = reactive({
    same_results: [],
    diff_results: [],
    missing_in_2: [],
    missing_in_1: [],
    counts: {same: 0, different: 0, missing_in_2: 0, missing_in_1: 0},
});

const activeTab = ref('same');

// 选中的复选框
const selectedItems = ref([]);

// 进度条相关
const progressVisible = ref(false);
const progressAction = ref('');
const progressPercent = ref(0);
const progressCompleted = ref(0);
const progressTotal = ref(0);


// 对比相关
const compareVisible = ref(false);
const compareLeftSrc = ref('');
const compareRightSrc = ref('');
// 对比相关
const openCompareModal = (fileName, leftSrc, rightSrc) => {
    compareVisible.value = true;
    compareLeftSrc.value = getMediaSrc(leftSrc, fileName);
    compareRightSrc.value = getMediaSrc(rightSrc, fileName);
};

// 计算属性
const counts = computed(() => {
    console.log('counts', results.counts)
    if (!results) {
        return {same: 0, different: 0, missing_in_2: 0, missing_in_1: 0};
    }
    console.log('counts', results.counts)
    return {
        same: results.counts?.same || 0,
        different: results.counts?.different || 0,
        missing_in_2: results.counts?.missing_in_2 || 0,
        missing_in_1: results.counts?.missing_in_1 || 0
    };
});

const selectedCount = computed(() => selectedItems.value.length);

const selectedLeftCount = computed(() =>
    selectedItems.value.filter(item => item.side === 'left').length
);

// 处理表单提交
const handleSubmit = async () => {
    // 清空当前选中
    selectedItems.value = [];

    loading.value = true;
    loadingResults.value = true;
    results.same_results = [];
    results.diff_results = [];
    results.missing_in_1 = [];
    results.missing_in_2 = [];

    try {
        const response = await fetch('/api/compare', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                folder1: formState.folder1.trim(),
                folder2: formState.folder2.trim()
            })
        });

        const data = await response.json();

        if (data.success) {
            Object.assign(results, data.data);
            loadingResults.value = false;
            console.log("对比结果:", results)
        } else {
            Message.error(`对比失败：${data.msg || '未知错误'}`,);
        }
    } catch (err) {
        console.error("对比失败:", err);
        Message.error(`对比失败：${err.message || '未知错误'}`);
    } finally {
        loading.value = false;
    }
};

// 处理标签切换
const handleTabChange = (key) => {
    activeTab.value = key;
    // 切换标签时，只保留当前标签的选中状态
    const currentTabResults = getCurrentTabResults();
    selectedItems.value = selectedItems.value.filter(item =>
        currentTabResults.some(r => r.name === item.name)
    );
};

// 获取当前标签的结果数据
const getCurrentTabResults = () => {
    if (!results) return [];

    switch (activeTab.value) {
        case 'same':
            return results.same_results || [];
        case 'different':
            return results.diff_results || [];
        case 'missing_in_2':
            return results.missing_in_2 || [];
        case 'missing_in_1':
            return results.missing_in_1 || [];
        default:
            return [];
    }
};

// 处理复选框变化
const handleCheckboxChange = (itemData) => {
    if (itemData.checked) {
        // 添加到选中列表
        if (!selectedItems.value.some(item =>
            item.name === itemData.name && item.side === itemData.side
        )) {
            selectedItems.value.push(itemData);
        }
    } else {
        // 从选中列表移除
        selectedItems.value = selectedItems.value.filter(item =>
            !(item.name === itemData.name && item.side === itemData.side)
        );
    }
};

// 全选
const selectAll = () => {
    const currentTabResults = getCurrentTabResults();
    if (!currentTabResults.length) return;

    // 清空当前选中
    selectedItems.value = [];

    // 根据当前标签添加选中项
    currentTabResults.forEach(item => {
        if (activeTab.value === 'same' || activeTab.value === 'different') {
            selectedItems.value.push({
                name: item.name,
                side: 'left',
                status: activeTab.value,
                checked: true
            });
            selectedItems.value.push({
                name: item.name,
                side: 'right',
                status: activeTab.value,
                checked: true
            });
        } else if (activeTab.value === 'missing_in_2') {
            selectedItems.value.push({
                name: item.name,
                side: 'left',
                status: activeTab.value,
                checked: true
            });
        } else if (activeTab.value === 'missing_in_1') {
            selectedItems.value.push({
                name: item.name,
                side: 'right',
                status: activeTab.value,
                checked: true
            });
        }
    });
};

// 取消全选
const unselectAll = () => {
    selectedItems.value = [];
};

// 勾选指定侧
const selectSide = (side) => {
    const currentTabResults = getCurrentTabResults();
    if (!currentTabResults.length) return;

    // 清空当前选中
    selectedItems.value = selectedItems.value.filter(item => item.side !== side);

    // 添加指定侧的选中项
    currentTabResults.forEach(item => {
        if (activeTab.value === 'same' || activeTab.value === 'different') {
            selectedItems.value.push({
                name: item.name,
                side: side,
                status: activeTab.value,
                checked: true
            });
        } else if (
            (activeTab.value === 'missing_in_2' && side === 'left') ||
            (activeTab.value === 'missing_in_1' && side === 'right')
        ) {
            selectedItems.value.push({
                name: item.name,
                side: side,
                status: activeTab.value,
                checked: true
            });
        }
    });
};

// 批量操作
const batchAction = async (action) => {
    if (selectedItems.value.length === 0) {
        Message.warning('请先选择文件');
        return;
    }
    progressAction.value = action;
    await performBatchRequest(action);
};


// 执行批量请求（带进度条和并发控制）
const performBatchRequest = async () => {
    const endpoint = '/api/batch-action';
    let completed = 0;
    let action = progressAction.value;
    const files = selectedItems.value.map(item => ({
        name: item.name,
        side: item.side,
        status: item.status
    }));

    // 过滤：move 操作只处理 left 文件
    const validFiles = action === 'move'
        ? files.filter(f => f.side === 'left')
        : files;

    if (validFiles.length === 0) {
        Message.warning('没有有效的文件可操作。');
        return;
    }

    // 重置并显示进度条
    progressVisible.value = true;
    progressTotal.value = validFiles.length;
    progressCompleted.value = 0;
    progressPercent.value = 0;

    // 更新进度函数
    const updateProgress = () => {
        completed++;
        const percent = Math.round((completed / validFiles.length) * 100);
        progressCompleted.value = completed;
        progressPercent.value = percent;

        if (completed === validFiles.length) {
            setTimeout(() => {
                progressVisible.value = false;
            }, 1000);
        }
    };

    // 并发发送所有请求
    const requests = validFiles.map(file =>
        fetch(endpoint, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                action,
                files: file, // 后端接口是否接受单个文件？若接受数组可改为 validFiles
                folder1: formState.folder1,
                folder2: formState.folder2,
            })
        }).then(res => {
            // 检查 HTTP 状态码是否成功（如 200-299）
            if (!res.ok) {
                throw new Error(`HTTP ${res.status}: ${res.statusText}`);
            }
            return res.json(); // 解析 JSON 数据
        }).then(res => {
            console.log('rrrr', res)
            updateProgress();
            return {success: res.data.success, ...res.data.msg, name: file.name};
        }).catch(err => {
            updateProgress();
            console.error(`Error processing ${file.name}:`, err);
            return {
                success: false,
                message: err.response?.data?.msg || err.message,
                name: file.name
            };
        })
    );

    // 等待所有完成
    try {
        const results = await Promise.all(requests);
        const successes = results.filter(r => r.success);
        const failures = results.filter(r => !r.success);

        if (failures.length === 0) {
            Message.success(`✅ 成功${action === 'move' ? '移动' : '删除'} ${successes.length} 个文件`);
        } else if (successes.length === 0) {
            Message.error(`❌ 所有文件操作失败，请查看控制台`);
        } else {
            Message.warning(`⚠️ 部分文件操作失败：成功 ${successes.length}，失败 ${failures.length}`);
            console.warn("失败详情：", failures);
        }
        // 刷新数据
        await handleSubmit();
    } catch (err) {
        Message.error('批量操作请求异常');
        console.error(err);
    }
};

</script>

<style scoped>
.app-container {
    height: 100vh;
    display: flex;
    flex-direction: column;
}

.header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
    background-color: #409eff;
    color: white;
}

.logo {
    font-size: 18px;
    font-weight: bold;
}

.content {
    flex: 1;
    padding: 20px;
    background-color: #f5f5f5;
}

.content-wrapper {
    max-width: 1600px;
    margin: 0 auto;
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.components-demo {
    margin-top: 20px;
}

.component-item {
    margin-bottom: 30px;
}

.component-item h3 {
    margin-bottom: 15px;
    color: #333;
    border-left: 4px solid #409eff;
    padding-left: 10px;
}

.footer {
    text-align: center;
    padding: 10px;
    background-color: #f0f0f0;
}

.mt-3 {
    margin-top: 3px;
}

.mr-3 {
    margin-right: 3px;
}

.mt-10 {
    margin-top: 10px;
}

.tab-content {
    padding: 16px;
}

.text-center {
    text-align: center;
}

.img-show {
    width: 100%;
}

.img-show img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

/* 表单吸顶样式 */
.sticky-form-wrapper {
    position: sticky;
    top: 0;
    z-index: 100;
    background: white;
    border-radius: 8px;
    transform: translateZ(0); /* 优化性能，开启硬件加速 */
}

.tab-container {
    overflow: auto;
    overflow-anchor: none; /* 防止滚动锚点干扰 */
    height: 940px;
}
</style>



